from dbutils.pooled_db import PooledDB
import pymysql


class DBPool:
    def __init__(self):
        self.pool = PooledDB(
            creator=pymysql,
            host='192.168.4.19',
            port=3306,
            user='root',
            password='1234',
            database='marvel_rivals',
            maxconnections=5,  # 最大连接数
            blocking=True,  # 连接池满时等待
            ping=1  # 每次使用前ping检查连接
        )

    def get_conn(self):
        """获取连接"""
        return self.pool.connection()


# 全局连接池实例
db_pool = DBPool()


def execute_query(sql, args=None):
    """执行查询（返回字典列表）"""
    with db_pool.get_conn() as conn:
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute(sql, args or ())
            return cursor.fetchall()


def execute_update(sql, args=None):
    """执行更新（返回影响行数）"""
    with db_pool.get_conn() as conn:
        with conn.cursor() as cursor:
            affected = cursor.execute(sql, args or ())
            conn.commit()
            return affected


# 测试连接
if __name__ == '__main__':
    try:
        result = execute_query("SELECT 1 AS test")
        print("✅ 数据库连接成功:", result)
    except Exception as e:
        print("❌ 连接失败:", str(e))